package edu.harding.redzone;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.util.Log;

public class Utility
{
	private static final String DATABASE_DROP_PLAY = "drop table if exists play";
	private static final String CREATE = "create table if not exists ";
	public final static String ID = "_id";
	public final static String PLAY = "play";
	public final static String TYPE = "type";
	public final static String NAME = "name";

	public final String DATABASE_NAME = "play.db";

	private SQLiteDatabase mDB;

	private ArrayList<ExistingPlay> mPlays = new ArrayList<ExistingPlay>();

	private final static String mSDCardPath = Environment
			.getExternalStorageDirectory() + "/Red Zone";
	private static Bitmap mBitmap;

	private final static String TAG = "Red Zone";

	private File mFile;
	private FileOutputStream mFos;

	private ExistingPlay mExisting;
	private Context mContext;

	public String SDCard()
	{
		return mSDCardPath;
	}

	public boolean EnsureSDCardAccess()
	{
		mFile = new File(mSDCardPath);
		if (mFile.exists())
		{
			return true;
		} else if (mFile.mkdirs())
		{
			return true;
		}
		return false;
	}

	public Utility(Context context)
	{
		mContext = context;
		openDB(mContext);
		closeDB();
	}

	private void openDB(Context context)
	{
		DBHelper db = new DBHelper(context, DATABASE_NAME);
		mDB = db.getWritableDatabase();
	}

	private void closeDB()
	{
		mDB.close();
	}

	public void SavePlay(Play play, Bitmap bitmap, Paint paint, int width,
			int height)
	{
		if (EnsureSDCardAccess())
		{
			openDB(mContext);
			try
			{
				mBitmap = Bitmap.createBitmap(width, height,
						Bitmap.Config.ARGB_8888);

				draw(play, bitmap, paint);

				mFile = new File(SDCard() + "/" + play.Name() + ".png");
				mFos = new FileOutputStream(mFile);
				mBitmap.compress(Bitmap.CompressFormat.PNG, 100, mFos);
				mFos.close();

				insertPlay(play.Name(), play.Type());
			} catch (FileNotFoundException e)
			{
				Log.e(TAG, "FileNotFoundException", e);
			} catch (IOException e)
			{
				Log.e(TAG, "IOEception", e);
			}
			
			closeDB();
		}
	}

	public ArrayList<ExistingPlay> GetPlays()
	{
		openDB(mContext);
		ArrayList<ExistingPlay> play = new ArrayList<ExistingPlay>();
		Cursor cursor = getPlays();
		mPlays.clear();

		cursor.moveToFirst();
		while (cursor.isAfterLast() == false)
		{
			mExisting = new ExistingPlay(cursor.getString(1),
					cursor.getString(2));
			mPlays.add(mExisting);
			cursor.moveToNext();
		}
		cursor.close();

		if (EnsureSDCardAccess())
		{
			for (int i = 0; i < mPlays.size(); i++)
			{
				mFile = new File(SDCard() + "/" + mPlays.get(i).Name() + ".png");
				if (!mFile.exists())
					play.add(mPlays.get(i));
			}
		}
		closeDB();

		return play;
	}

	public void DeletePlay(String name)
	{
		if (EnsureSDCardAccess())
		{
			openDB(mContext);
			mFile = new File(SDCard() + "/" + name + ".png");
			if (mFile.exists())
				if (mFile.delete())
					deletePlay(name);
			
			closeDB();
		}
	}

	private Cursor getPlays()
	{
		String sql = "SELECT * FROM play ORDER BY name ASC";
		return mDB.rawQuery(sql, null);
	}

	private void draw(Play play, Bitmap bitmap, Paint paint)
	{
		Canvas canvas = new Canvas(mBitmap);
		canvas.drawColor(Color.WHITE);
		for (Player player : play.Players())
		{
			canvas.drawBitmap(bitmap, player.X(), player.Y(), null);
			canvas.drawPath(player.PathRoute().Path(), paint);
			canvas.drawLines(player.Line(), paint);
			canvas.drawOval(player.Oval(), paint);
		}
	}

	private void deletePlay(String name)
	{
		String sql = "DELETE FROM play WHERE name = '" + name + "'";
		mDB.rawQuery(sql, null);
	}

	private long insertPlay(String name, String type)
	{
		ContentValues values = new ContentValues();
		values.put(TYPE, type);
		values.put(NAME, name);
		return mDB.insert(PLAY, null, values);
	}

	public static class DBHelper extends SQLiteOpenHelper
	{

		private static final String CREATE_TABLE_PLAY = CREATE + PLAY + "("
				+ ID + " integer primary key autoincrement, " + TYPE
				+ " varchar(10) not null, " + NAME
				+ " varchar(50) not null unique); ";

		public DBHelper(Context context, String name)
		{
			super(context, name, null, 1);
		}

		@Override
		public void onCreate(SQLiteDatabase db)
		{
			db.execSQL(CREATE_TABLE_PLAY);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
		{
			db.execSQL(DATABASE_DROP_PLAY);
		}

	}
}
